<?PHP

class article{

	var $id				= null;
	var $authorID		= null;
	var $articleData	= "";
	var $title 			= "";
	var $keywords 		= "";
	var $approved		= "";
	var $views			= "";
	var $rating			= "";
	var $ratedCount		= "";
	var $dateSubmitted	= "";

	/********************************************
	* Creation and loading Methods
	*
	* __construct($id)
	*	- Constructor
	*
	* _load($id)
	*	- loads the data
	*
	* parent()
	* 	- Returns teh parent article if applicable
	*
	* author()
	*	- Returns an author class of the article author.  or false on no author
	*
	* attachments()
	*	- Returns an array of attachments for the article
	*
	* related()
	*	- Returns related articles in an array
	*
	* comments()
	*	- Returns all commetns ina an array
	*
	********************************************/

	function __construct($id = null){
		$this->_load($id);
	}

	function _load($id){
		$sql = "SELECT * FROM articles WHERE FileID = ?";
		$parms = array($id);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);
		if($row = $query->fetch()){
			$this->id			= $row['FileID'];
			$this->authorID		= $row['AuthorID'];
			$this->articleData	= $row['Articledata'];
			$this->title 		= $row['Title'];
			$this->keywords		= $row['Keyw'];
			$this->approved		= $row['Approved'];
			$this->views		= $row['Views'];
			$this->rating		= $row['RatingTotal'];
			$this->ratedCount	= $row['RatedTotal'];
			$this->dateSubmitted= $row['SubmitDate'];

			return true;
		}

		return false;
	}

	function parent(){
		$sql = "SELECT FileID FROM articles WHERE Approved='A' AND ParentID=? LIMIT 1";
		$parms = array($this->id);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);
		if($row = $query->fetch()){
			return article::load($row['FileID']);
		}

		return false;
	}

	function author(){
		if($this->authorID == 0 || $this->authorID == "")
			return false;

		return author::load($this->authorID);
	}

	function attachments(){
		$sql = "SELECT UploadID, AuthorID, FileName, FileDescription, FileID FROM uploads WHERE FileID=?";
		$parms = array($this->id);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);

		return $query->fetchAll();
	}

	function related($count = 10){
		if(trim($this->keywords) == '')
			return array(); // no keywords nothing to search

		$sql = "SELECT FileID, Title FROM articles WHERE MATCH(Keyw) AGAINST (?) AND parentID = 0 AND Approved = 'Y' AND FileID != ? ORDER BY MATCH(Keyw) AGAINST (?) DESC LIMIT ".$count;
		$parms = array($this->keywords, $this->id, $this->keywords);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);

		return $query->fetchAll();
	}

	function comments(){
		$sql = "SELECT FileID, Title, SubmitDate, Articledata FROM articles WHERE Approved='Y' AND ParentID=? ORDER BY SubmitDate";
		$parms = array($this->id);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);

		return $query->fetchAll();
	}

	/********************************************
	* Factory Methods
	*
	* create($title, $userID, $articledata, $keywords, $parent = false, $type = "N")
	*	- Creates a new article returns true/false based on success / failure
	* 	- $parent is optional and is used to specify a parent question
	*
	* load($id)
	* 	- loads an article, returns false on failure
	*
	********************************************/

	public static function create($title, $userID, $articledata, $keywords, $parent = false, $type = "N"){

		$sql = 'INSERT INTO articles (Title, AuthorID, Articledata, Keyw, Approved) VALUES (?, ?, ?, ?, ?)';
		$parms = array($title, $userID, $articledata, $keywords, $type);
		if($GLOBALS['db']->prepare_execute($sql, $parms)){
			$a = article::load( $GLOBALS['db']->lastInsertId() );
		}else{
			return false;
		}

		if($a && $parent){
			$sql = "UPDATE articles SET ParentID = ?, Approved = 'A' WHERE FileID = ?";
			$parms = array($a->id, $parent);
			$GLOBALS['db']->prepare_execute($sql, $parms);
		}

		return $a;
	}

	public static function load($id){
		$a = new article($id);
		if($a->id)
			return $a;

		return false;
	}

	/********************************************
	* Editing Methods
	*
	* update($title, $articledata, $keywords)
	*	- allows the user to update an article they wrote
	*
	* add_file($fileTmpName, $fileName, $fileType, $fileDesc, $userID)
	*	- Adds and moves a file into the attach folder
	* 	- returns true/false on succes/failure
	*
	* incrementViews()
	*	- Increments views on article by 1
	*
	* addScore($score)
	*	- Adds the given score to the total
	*
	* addComment($title, $comment, $author = false)
	*	- Returns an article class of the newly created comment.
	*
	* update_keywords()
	*	- Updated the articles keywords in the tags table
	*
	* approve()
	*	- Approves an article or comment
	*
	* delete()
	*	- Deletes an article
	*
	********************************************/

	function update($title, $articledata, $keywords){
		$sql = "UPDATE articles SET Title = ?, Articledata = ?, Keyw = ? WHERE FileID = ?";
		$parms = array($title, $articledata, $keywords, $this->id);
		if($GLOBALS['db']->prepare_execute($sql, $parms)){
			$this->_load($this->id);
			$this->update_keywords();
			return true;
		}
		return false;
	}

	function add_file($fileTmpName, $fileName, $fileType, $fileDesc, $userID){
		//TODO check file type
		$sql = "INSERT INTO uploads (AuthorID, FileID, FileName, FileType, FileDescription, UploadDate) VALUES (?, ?, ?, ?, ?, NOW())";
		$parms = array($userID , $this->id, $fileName , $fileType, $fileDesc);
		$GLOBALS['db']->prepare_execute($sql, $parms);

		$uid = $GLOBALS['db']->lastInsertId();
		$filename = $uid . '-' . $userID . '-' . $this->id . '-' . $fileName;

		if(!move_uploaded_file($fileTmpName, POMBY_DIR . "/attach/$filename")){
			$sql = "DELETE FROM uploads WHERE UploadID = ?";
			$parms = array($uid);
			$GLOBALS['db']->prepare_execute($sql, $parms);

			return false;
		}

		return true;
	}

	function del_file($fid){
		$sql = "SELECT UploadID, AuthorID, FileName, FileDescription, FileID FROM uploads WHERE FileID = ? AND UploadID = ?";
		$parms = array($this->id, $fid);
		$query = $GLOBALS['db']->prepare_execute($sql, $parms);
		if($a = $query->fetch()){
			$filename = "{$a['UploadID']}-{$a['AuthorID']}-{$a['FileID']}-{$a['FileName']}";
			if(unlink(POMBY_DIR . "/attach/" . $filename)){
				$sql = "DELETE FROM uploads WHERE FileID = ? AND UploadID = ?";
				$parms = array($this->id, $fid);
				$GLOBALS['db']->prepare_execute($sql, $parms);

				return true;
			}
		}

		return false;
	}

	function incrementViews(){
		if($this->approved != "Y")
			return;

		$sql = "UPDATE articles SET Views = Views + 1 WHERE FileID = ?";
		$parms = array($this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		// no return; this is unimportant if it fails
	}

	function addScore($score){
		$sql = "UPDATE articles SET RatingTotal = RatingTotal + ?, RatedTotal = RatedTotal + 1 WHERE FileID = ?";
		$parms = array($score, $this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		// no return; this is unimportant if it fails
	}

	function addComment($title, $comment, $author = false){
		if(!$author)
			$author = 0;
		$sql = "INSERT INTO articles (ParentID, Title, Articledata, AuthorID, SubmitDate) VALUES (?, ?, ?, ?, NOW())";
		$parms = array($this->id, $title, $comment, $author);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		return(article::load( $GLOBALS['db']->lastInsertId() ));
	}

	function update_keywords(){
		if($this->approved != 'Y')
			return false;

		$sql = "DELETE FROM tags WHERE FileID = ?";
		$parms = array($this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);

		$ky = explode(" ", $this->keywords);
		$sql = "INSERT INTO tags (fileid, tag) VALUES (?, ?)";
		$query = $GLOBALS['db']->prepare($sql);

		foreach($ky as $v){
			if(strlen(trim($v)) > 2){
				$query->execute(array($this->id, trim($v)));
			}
		}

		return true;
	}

	function approve(){
		if($this->approved == 'N'){
			$sql = "UPDATE articles SET Approved='Y' where FileID=? LIMIT 1";
			$parms = array($this->id);
			$GLOBALS['db']->prepare_execute($sql, $parms);

			$this->_load($this->id);
			$this->update_keywords();
		}else{
			return false;
		}
	}

	function delete(){
		// Delete
		$sql = "DELETE from articles WHERE FileID=?";
		$parms = array($this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		// Delete Children
		$sql = "DELETE from articles WHERE ParentID=?";
		$parms = array($this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		// Delete Tags
		$sql = "DELETE from tags WHERE FileID=?";
		$parms = array($this->id);
		$GLOBALS['db']->prepare_execute($sql, $parms);
		// TODO: Delete Attachments

		return true;
	}
}

?>